<?php
namespace app\utils\wx;


use app\lib\exception\WxApiException;
use app\utils\CurlRequest;

class WXMiniLogin
{

    const JSCODE2SESSION_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&";
    private $appid;
    private $secret;

    public function __construct()
    {
        $this->appid = env('wxmini.appId');
        $this->secret = env('wxmini.secret');

    }
    

    public function jscode2session($js_code)
    {
        $url = sprintf("%sappid=%s&secret=%s&js_code=%s", self::JSCODE2SESSION_URL, $this->appid, $this->secret, $js_code);

        $wxJson = (new CurlRequest())->get_json($url);
        $wxResult = json_decode($wxJson, true);

        if (array_key_exists('errcode', $wxResult))
        {
            //抛出微信接口错误
            throw new WxApiException($wxJson);
        }

        return $wxResult['openid'];
    }
}